package com.stud.seckill.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.stud.seckill.common.config.RedisService;
import com.stud.seckill.entity.UserEntity;
import com.stud.seckill.service.LoginService;
import com.stud.seckill.service.UserService;
import com.stud.seckill.common.utils.MD5Util;
import com.stud.seckill.entity.vo.LoginVo;
import com.stud.seckill.common.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    @Transactional
    @Override
    public R<String> doLogin(LoginVo entity, HttpServletResponse response) {
        UserEntity user = userService.get(entity.getMobile());
        if (user == null) {
            return R.fail("用户名不存在");
        }

        // Alt + F8 可以看某一段代码的执行结果
        if (!MD5Util.formPassToDBPass(entity.getPassword(), user.getSalt()).equals(user.getPassword())) {
            return R.fail("密码错误");
        }

        // 用户名密码都正确，登录成功
        String ticket = IdUtil.fastSimpleUUID();

        StpUtil.login(user.getId());
        /*redisService.set(Constant.TICKET_CACHE_KEY + ticket, user, Constant.MAX_AGE_IN_SECONDS);
        if (response != null) {
            ServletUtil.addCookie(response, Constant.COOKIE_TICKET_KEY, ticket, Constant.MAX_AGE_IN_SECONDS);
        }*/

        // 记录登录时间及次数
        userService.loginSuccess(user.getId());

        return R.success(ticket);
    }

}
